package com.ruoyi.web.core.config;

import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.system.mqtt.MqttClientSelfDefine;
import io.moquette.broker.Server;
import io.moquette.broker.config.ClasspathResourceLoader;
import io.moquette.broker.config.IConfig;
import io.moquette.broker.config.ResourceLoaderConfig;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.util.List;

@Configuration
@Slf4j
public class MqttConfig {

    @Value("${mqtt.broker.url}")
    private String brokerUrl;

    @Value("${mqtt.client.id}")
    private String clientId;

    @Value("${mqtt.topic.name}")
    private String topicName;

    @Autowired
    private RedisCache redisCache;

    @Bean
    public MqttClient mqttClient() throws MqttException {
        MqttClient client = new MqttClient(brokerUrl, clientId);
        MqttConnectOptions options = new MqttConnectOptions();
        options.setAutomaticReconnect(true);
        options.setCleanSession(true);
        // 客户端连接mqtt
        client.connect(options);
        log.info("Connected to the MQTT broker");
        // 自定义mqtt客户端回调
        MqttClientSelfDefine mqttCallback = new MqttClientSelfDefine(redisCache);
        client.setCallback(mqttCallback);
        return client;
    }

    static {
        try {
            init();
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (MqttException e) {
            throw new RuntimeException(e);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    public static void init() throws IOException, MqttException, InterruptedException {
        // 加载配置文件（默认从classpath读取moquette.conf）
        IConfig config = new ResourceLoaderConfig(new ClasspathResourceLoader());

        // 初始化Broker
        Server mqttBroker = new Server();
        mqttBroker.startServer(config);

        // 添加关闭钩子
        Runtime.getRuntime().addShutdownHook(new Thread(mqttBroker::stopServer));
        log.info("MQTT Broker启动成功，监听端口: " + config.getProperty("port"));


        // 创建客户端
//        createClient();
    }
}



